package com.test.mchelepesa.util_rice.http_rice.connection;

import com.test.mchelepesa.constant_rice.Constant_rice
import java.io.*
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.ExecutorService
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import javax.net.ssl.HttpsURLConnection
import kotlin.math.min

/** 专门处理打点线程池 */
class PointHttpConnection(private val fullUrl: String, private val body: String) {

    companion object {
        private var cpuCount: Int = Runtime.getRuntime().availableProcessors() + 1
        private var calculatedMax: Int = cpuCount * 2 + 1
        private var maxPoolSize: Int = min(8, calculatedMax)

        private val cachedThreadPool: ExecutorService = ThreadPoolExecutor(
            0, // 线程池空闲时会不保留线程
            maxPoolSize, // 最大并发线程数
            60L, // 线程空闲时最大存活时间
            TimeUnit.SECONDS, // 空闲时间单位
            LinkedBlockingQueue(10), // 队列大小，最多允许 16 个任务排队
            ThreadPoolExecutor.DiscardPolicy() // 任务队列已满时丢弃任务
        )

        fun shutdown() {
            try {
                cachedThreadPool.shutdownNow()
            } catch (_: Exception) {
            }
        }
    }

    fun fetch(silent: Boolean = true) {
        cachedThreadPool.execute {
            try {
                val urlConnection = initConnection()
                urlConnection.outputStream?.use { os ->
                    os.write(body.toByteArray(Charsets.UTF_8))
                    os.flush()
                    os.close()
                }
                try {
                    val resCode = urlConnection.responseCode
                    if (resCode == HttpURLConnection.HTTP_OK) {
                        // 如果不需要处理回调，直接退出
                        if (silent) return@execute
                    }
                } catch (e: Exception) {
                    // 如果不需要处理回调，直接退出
                    if (silent) return@execute

                } finally {
                    try {
                        urlConnection.inputStream.close()
                        urlConnection.disconnect()
                    } catch (_: Exception) {
                    }
                }
            } catch (e: IOException) {
                // 如果不需要处理回调，直接退出
                if (silent) return@execute
                // StringUtil_rice.printException(e)
            }
        }
    }

    @Throws(IOException::class)
    private fun initConnection(method: String = "POST"): HttpURLConnection {
        val url = URL(this.fullUrl)
        val urlConnection = url.openConnection() as HttpsURLConnection
        urlConnection.doInput = true
        urlConnection.doOutput = true
        urlConnection.useCaches = false
        urlConnection.readTimeout = 60000
        urlConnection.connectTimeout = 60000
        urlConnection.requestMethod = method
        urlConnection.setRequestProperty("Charset", "UTF-8")
        urlConnection.setRequestProperty("Connection", "Keep-Alive")
        urlConnection.setRequestProperty("Content-Type", "application/json")
        urlConnection.setRequestProperty("product", Constant_rice.PRODUCT)
        return urlConnection
    }
}
